package cn.com.hfuu.control;

import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.hfuu.SystemUtil;
import cn.com.hfuu.VcodeUtil;
import cn.com.hfuu.module.menu;
import cn.com.hfuu.module.role;
import cn.com.hfuu.module.user;
import cn.com.hfuu.service.RoleMenuService;
import cn.com.hfuu.service.UserService;
import cn.com.hfuu.service.UserroleService;

@Controller
@RequestMapping("/login")
public class LoginControl {

	@Autowired
	private UserService userService;
	@Autowired
	private UserroleService userroleService;

	@Autowired
	private RoleMenuService rolemenuservice;

	SystemUtil systemutil = new SystemUtil();

	/**
	 * 跳转到登陆界面
	 * 
	 * @return
	 */
	@RequestMapping("/home")
	public String home() {
		return "login/login";
	}

	/**
	 * 产生一次性验证码
	 * 
	 * @param response
	 * @param session
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	@RequestMapping("/code")
	public void code(HttpServletResponse response, HttpSession session)
			throws FileNotFoundException, IOException {
		VcodeUtil codeutil = new VcodeUtil();

		BufferedImage img = codeutil.getimg();
		session.setAttribute("code", codeutil.getCode());
		response.setContentType("image/png");
		OutputStream os = response.getOutputStream();
		ImageIO.write(img, "png", os);
	}

	/**
	 * 校验验证码
	 */
	@RequestMapping(value = "/checkcode", method = RequestMethod.POST)
	@ResponseBody
	public String checkCode(HttpSession session, String inputcode) {
		String c = (String) session.getAttribute("code");

		if (c.toLowerCase().equals(inputcode.toLowerCase().trim())) {
			return "{\"result\":true}";
		} else {
			return "{\"result\":false}";
		}
	}

	@RequestMapping("/dologin")
	public String username(HttpSession session, String username,
			String password, Model m) {
		if (username == null || password == null) {
			return "login/loginerror";
		}
		user u = userService.exitUser(username, password);
		if (u != null) {
			session.setAttribute("user", u);
			List<role> role = userroleService.selectbyuser(u.getUserId());
			List<menu> menulist = new ArrayList<menu>();
			for (role role2 : role) {
				menulist.addAll(rolemenuservice.selectbyrole(role2.getRoleId())); // 根据权限获取所有的菜单编号
			}
			List<menu> cflist = new ArrayList<menu>();
			// 去重复对象
			for (int i = 0; i < menulist.size() - 1; i++) {
				for (int j = menulist.size() - 1; j > i; j--) {
					if (menulist.get(i).getMenuId()
							.equals(menulist.get(j).getMenuId())) {
						cflist.add(menulist.get(j));
						menulist.remove(j);
					}

				}
			}

			Collections.sort(menulist, new Comparator<menu>() {
				@Override
				public int compare(menu o1, menu o2) {
					// TODO Auto-generated method stub
					if (o1.getMenuOrder() > o2.getMenuOrder()) {
						return 1;
					} else if (o1.getMenuOrder() == o2.getMenuOrder()) {
						return 0;
					} else {
						return -1;
					}

				}

			});
			List<menu> menufirst = new ArrayList<menu>();
			for (menu menu : menulist) {

				if (Long.parseLong(menu.getMenuParentid()) < 1) {// 一级菜单
					List<menu> secondlist = rolemenuservice.selectSeconnd(menu
							.getMenuId());// 一级菜单下所有二级菜单
					List<menu> second = new ArrayList<menu>();
					for (menu menu2 : menulist) {
						for (menu menu22 : secondlist) {
							if (menu2.getMenuId().equals(menu22.getMenuId())) {// 拥有权限的二级菜单
								second.add(menu2);
							}
						}
					}

					menu.setSecond(second);
					menufirst.add(menu);
				}
			}
			for (menu menu : menufirst) {
				System.out.println(menu.toString());
			}
			m.addAttribute("menulist", menufirst);
			return "login/index";
		} else {
			return "login/loginerror";
		}
	}

	@RequestMapping("/dologinad")
	@ResponseBody
	public List<role> usernamead(HttpSession session, String username,
			String password, Model m) {

		user u = userService.exitUser(username, password);
		if (u != null) {
			session.setAttribute("user", u);
			List<role> role = userroleService.selectbyuser(u.getUserId());
			return role;
		}
		return null;
	}

}
